package com.wing.order.controller.app;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.Cabinet;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.cabinet.model.response.CellSingleInventoryProductVO;
import com.wing.cabinet.service.CabinetCargoLaneService;
import com.wing.cabinet.service.CabinetService;
import com.wing.cabinet.service.CellSingleInventoryProductService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.company.model.entity.Company;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.order.model.entity.InventoryAlarm;
import com.wing.order.model.request.InventoryAlarmForm;
import com.wing.order.model.response.AlarmProductVo;
import com.wing.order.model.response.InventoryAlarmVO;
import com.wing.order.model.response.RecycleVo;
import com.wing.order.service.DistributionDemandPlanDetailService;
import com.wing.order.service.DistributionDemandPlanService;
import com.wing.order.service.InventoryAlarmService;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "App-库存告警管理", tags = "库存告警管理")
@RestController("appInventoryAlarmController")
@RequestMapping("order/app/inventoryAlarm")
@Slf4j
public class InventoryAlarmController {

    @Autowired
    private InventoryAlarmService inventoryAlarmService;
    @Autowired
    private LocaleMessage localeMessage;

    @Autowired
    private CabinetService cabinetService;

    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired
    private CabinetCargoLaneService cabinetCargoLaneService;

    @Autowired
    private DistributionDemandPlanService demandPlanService;

    @Autowired
    private DistributionDemandPlanDetailService distributionDemandPlanDetailService;

    @Autowired
    private CellSingleInventoryProductService cellSingleInventoryProductService;

    @ApiOperation(value = "查询所有告警信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CellSingleInventoryProductVO> list(
            @RequestParam( defaultValue = "1", required = false) Integer page
            , @RequestParam( defaultValue = "10", required = false) Integer limit
            , @RequestParam( defaultValue = "create_time", required = false) String sort
            , @RequestParam( defaultValue = "desc", required = false) String order
            , InventoryAlarm.Status status
            ,String mainCabCode
            ,String query
    ) {
        Page<CellSingleInventoryProductVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        if (status!=null){
            params.put("status",status.getValue());
        }
        params.put("mainCabCode",mainCabCode);
        if (StringUtils.isNotBlank(query)){
            params.put("query",query);
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        Page<CellSingleInventoryProductVO> list = cellSingleInventoryProductService.pageList4Alarm(pg, params);
        Integer no=1;
        Date date=new Date();
        if (CollectionUtil.isNotEmpty(list.getRecords())){
            for (CellSingleInventoryProductVO cellSingleInventoryProductVO:list.getRecords()){
                cellSingleInventoryProductVO.setCreateTime(LocalDateTime.now());
                cellSingleInventoryProductVO.setCode(simpleDateFormat.format(date)+"-"+StringUtils.leftPad(no.toString(),3,"0"));
            }
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/detail/{id}")
    public JsonResult detail(@PathVariable("id") Long inventoryAlarmId) {
        InventoryAlarmVO inventoryAlarmVO = inventoryAlarmService.get4appById(inventoryAlarmId);
        if (inventoryAlarmVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), inventoryAlarmVO);
    }

    @PostMapping()
    public JsonResult add(@Validated InventoryAlarmForm inventoryAlarmForm) {
        if (inventoryAlarmService.add(inventoryAlarmForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }


    /**
     * 库存列表
     * TODO  所属车间 楼层 为假数据
     */
    @GetMapping("/inventory")
    public PageResult<CabinetVO> inventory(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order
            , @RequestParam(name = "cabCode", defaultValue = "", required = false) String cabCode
            , Cabinet.CabinetNature cabinetNature
            ) {

        Page<CabinetVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        //筛选  TODO 车间名称
        if (StringUtils.isNotBlank(cabCode)) {
            params.put("cabCode", cabCode);
        }
        if (cabinetNature!=null){
            params.put("cabinetNature",cabinetNature.getValue());
        }
        Page<CabinetVO> list = cabinetService.inventory(pg, params);
        //根据查询出来的企业id 查询公司名称  settledCompanyId
        for (CabinetVO c : list.getRecords()) {
            JsonResult<Company> companyInfo = enterpriseClient.getCompanyInfo(c.getSettledCompanyId().toString());
            c.setCompanyName(companyInfo.getData().getName());
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 库存 告警产品
     *
     * @param cabCode 柜子编号
     */
    @GetMapping("/alarmProduct")
    public PageResult<InventoryAlarmVO> alarmProduct(@RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order
            , @RequestParam(name = "cabCode") String cabCode) {

        Page<InventoryAlarmVO> pg = new Page();
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        Page<InventoryAlarmVO> list = inventoryAlarmService.alarmProduct(pg, params, cabCode);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 告警产品 申请补货
     *
     * @param skuCode 产品sku
     * @param cabCode 柜子编号
     */
    @PutMapping("/applyRepair")
    public JsonResult applyRepair(@RequestParam(name = "skuCode") String skuCode,@RequestParam(name = "cabCode") String cabCode) {

         if (inventoryAlarmService.applyRepair(skuCode,cabCode)){
             return JsonResult.success("已提交申请");
         }else {
             return JsonResult.fail("提交失败");
         }
    }

    @ApiOperation(value = "申请补货（告警数据点击申请补货）", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "告警id", defaultValue = "1", example = "1", dataType = "Long", paramType = "query")
    })
    @GetMapping("/confirm")
    public JsonResult confirm(Long id){
        InventoryAlarmForm inventoryAlarmForm=new InventoryAlarmForm();
        try{
            inventoryAlarmForm.setId(id);
            inventoryAlarmService.confirm(inventoryAlarmForm);
            return JsonResult.success("提交成功");
        }catch (Exception e){
            log.error("confirm fail",e);
            return JsonResult.fail("提交失败");
        }
    }


    /**
     * 库存 告警产品 详情
     *
     * @param skuCode 产品编号
     */
    @GetMapping("/AlarmProductDetails")
    public JsonResult<AlarmProductVo> AlarmProductDetails(@RequestParam(value = "skuCode") String skuCode) {

        AlarmProductVo alarmProductVo = inventoryAlarmService.alarmProductDetails(skuCode);

        return JsonResult.success(alarmProductVo);
    }


    /**
     * 我的库存 柜子信息
     *
     * @param cabCode 柜子编号
     */
    @GetMapping("/myInventory")
    public JsonResult<CabinetVO> myInventory(@RequestParam(name = "cabCode") String cabCode) {

        CabinetVO cabinetVO = cabinetService.myInventory(cabCode,null);
        JsonResult<Company> companyInfo = enterpriseClient.getCompanyInfo(cabinetVO.getSettledCompanyId().toString());
        cabinetVO.setCompanyName(companyInfo.getData().getName());
        return JsonResult.success(cabinetVO);
    }


    /**
     * product 产品库存/ aisle 货道库存
     *
     * @param cabCode 柜子编号
     * @param type    判断是产品库存/货道库存
     */
    @GetMapping("/proInventory")
    public PageResult<AlarmProductVo> proInventory(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order
            , @RequestParam(name = "cabCode") String cabCode,
            @RequestParam("type") String type) {
        Page<AlarmProductVo> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        if ("product".equals(type)) {
            Page<AlarmProductVo> list = inventoryAlarmService.proInventory(pg, params, cabCode);
            return new PageResult<>(list.getRecords(), list.getTotal());
        }
        if ("aisle".equals(type)) {
            Page<AlarmProductVo> list = inventoryAlarmService.spaceInventory(pg, params, cabCode);
            return new PageResult<>(list.getRecords(), list.getTotal());
        }
        return null;
    }

    /**
     * 产品详情下的 货道号、数量
     *
     * @param cabCode 柜子编号
     * @param skuCode 产品编号
     */
    @GetMapping("/productDetails")
    public JsonResult<AlarmProductVo> productDetails(
            @RequestParam("skuCode") String skuCode,
            @RequestParam("cabCode") String cabCode
    ) {

        List<AlarmProductVo> alarmProductVo = inventoryAlarmService.productDetails(skuCode, cabCode);
        return JsonResult.success(alarmProductVo);
    }

    /**
     * 产品详情下的 货道号、数量
     *
     * @param cabCode 柜子编号
     * @param skuCode 产品编号
     */
    @GetMapping("/productDetails2")
    public JsonResult<AlarmProductVo> productDetails2(
            @RequestParam("skuCode") String skuCode,
            @RequestParam("cabCode") String cabCode
    ) {

        List<AlarmProductVo> alarmProductVo = inventoryAlarmService.productDetails2(skuCode, cabCode);
        return JsonResult.success(alarmProductVo);
    }


    /**
     * 告警信息 列表 -app
     */
    @GetMapping("/tellWarn")
    public PageResult<InventoryAlarmVO> tellWarn(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order
    ) {
        Page<InventoryAlarmVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        Page<InventoryAlarmVO> list = inventoryAlarmService.tellWarn(pg, params);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 回收信息 列表-app
     */
    @GetMapping("/recycleInfo")
    public JsonResult recycleInfo() {

        List<RecycleVo> list = inventoryAlarmService.recycleInfo();

        return JsonResult.success(list);
    }


}
